require('./mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var relationTypeSchema = Schema({
  relkey: { type: String, unique: true },
  name: { type: String },
  srcdesc: { type: String },
  destdesc: { type: String },
  dir: { type: String, default: 'src_to_dest' },
  buildin: { type: Boolean, default: false }
})

relationTypeSchema.statics = {
  init: function () {
    var list = [
      { "relkey": "belong", "name": "属于", "srcdesc": "属于", "destdesc": "包含", "dir": "src_to_dest", "buildin": true },
      { "relkey": "group", "name": "组成", "srcdesc": "组成", "destdesc": "组成于", "dir": "src_to_dest", "buildin": true },
      { "relkey": "run", "name": "运行", "srcdesc": "运行于", "destdesc": "运行", "dir": "src_to_dest", "buildin": true },
      { "relkey": "connect", "name": "连接", "srcdesc": "连接在", "destdesc": "接入了", "dir": "src_to_dest", "buildin": true },
      { "relkey": "default", "name": "默认关联", "srcdesc": "关联", "destdesc": "关联", "dir": "src_to_dest", "buildin": true },
      { "relkey": "install", "name": "放置", "srcdesc": "放置在", "destdesc": "包含", "dir": "src_to_dest", "buildin": true }
    ]
    RelationType.count((err, count) => {
      if (count == 0) {
        RelationType.create(list);
      }
    })
  },
  page: function (query, page, limit, callback) {
    if (page === undefined) page = 0
    if (limit === undefined) limit = 20
    RelationType.count(query).then(total => {
      RelationType.find(query).skip((page) * limit).limit(limit * 1).exec().then((docs) => {
        callback({
          pageable: {
            totalElements: total,
            numberOfElements: docs.length,
            totalPages: Math.ceil(total / limit),
            number: page,
            first: page == 0,
            last: docs.length < limit || (docs.length === limit && (page + 1) * limit >= total),
            size: limit,
            fromNumber: page * limit,
            toNumber: page * limit + docs.length
          },
          docs
        })
      })
    })
  }
}

var RelationType = mongoose.model('RelationType', relationTypeSchema);

module.exports = RelationType
